package com.mtw.bbs.bbsUser.controller.open;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mtw.bbs.article.feign.LikeClient;
import com.mtw.bbs.bbsUser.pojo.elasticsearch.UserESIndex;
import com.mtw.bbs.bbsUser.pojo.entity.User;
import com.mtw.bbs.bbsUser.pojo.vo.UserCountVO;
import com.mtw.bbs.bbsUser.pojo.vo.UserDetailsVo;
import com.mtw.bbs.bbsUser.service.UserFollowService;
import com.mtw.bbs.bbsUser.service.UserService;
import com.mtw.bbs.bbsUser.utils.AvatarUtilz;
import com.mtw.bbs.common.core.constant.SysConstant;
import com.mtw.bbs.common.core.exception.BusinessException;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.userAdmin.pojo.form.UserRegisterForm;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 用户接口层
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("open/user")
public class OpenUserController {


    private final LikeClient likeClient;
    private final UserService userService;
    private final AvatarUtilz avatarUtilz;
    private final UserFollowService userFollowService;
    private final ElasticsearchTemplate elasticsearchTemplate;





    @PostMapping("/register")
    @ApiOperation(value = "注册用户", notes = "传入表单信息")
    public Result registerUser(@RequestBody UserRegisterForm form) {

        try {
            User user = new User();
            BeanUtils.copyProperties(form,user);
            userService.registerUser(user);
        }catch (BusinessException e){
            return Result.fail(e.getMessage());
        }
        return Result.success();
    }




    /**
     * 获取当前用户的关注数与粉丝数和点赞数
     *
     */
    @GetMapping(value = "/ffl_count/{username}")
    public Result getUserFollowLikeAndFansCount(@PathVariable("username") String username) {

        User user = userService.getUserInfoByUsername(username);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        UserCountVO vo = new UserCountVO();
        Result<Integer> userLikeCount = likeClient.getUserLikeCount(user.getUsername());
        if (userLikeCount.isSuccess()) {
            vo.setLike(userLikeCount.getData());
        }
        Integer follow = userFollowService.countOfFollow(user.getId());
        Integer fans = userFollowService.countOfFans(user.getId());
        vo.setFans(fans);
        vo.setFollow(follow);
        return Result.success(vo);
    }




    /**
     * 根据username获取用户信息
     */
    @ApiOperation(value = "获取用户信息", notes = "传入用户username")
    @GetMapping("/getUserInfo/{username}")
    public Result<UserDetailsVo> getUserInfo(@PathVariable("username") String username) {

        User user = userService.getUserInfoByUsername(username);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        UserDetailsVo vo = new UserDetailsVo();
        BeanUtils.copyProperties(user, vo);
        avatarUtilz.setAvatarUrl(vo);
        vo.setPhone(null);
        UserDetails currentUser = SecurityContextHolder.getContext().getAuthentication();
        if (currentUser != null && !user.getId().equals(currentUser.getId())){
            vo.setFollowed(userFollowService.getIsFollowed(currentUser.getId(),user.getId()));
        }
        return Result.success(vo);
    }



    /**
     *  获取当前用户信息
     */
    @ApiOperation(value = "获取当前用户信息", notes = "")
    @GetMapping("/getCurrentInfo")
    public Result<UserDetailsVo> getCurrentInfo() {

        UserDetails currentUser = SecurityContextHolder.getContext().getAuthentication();
        if (currentUser == null){
            return Result.fail("请登录");
        }
        return getUserInfo(currentUser.getUsername());
    }



    /**
     * 搜索话题
     *
     * @param page 当前页
     * @param size 分页大小
     */
    @GetMapping("/search")
    public Result selectTopic(@RequestParam(name = "page") int page,
                              @RequestParam(name = "size") int size,
                              @RequestParam(name = "keyword",required = false) String keyword) {

        if (StringUtils.isBlank(keyword)) {
            return Result.fail("请输入关键词");
        }

        // 查询构建
        NativeQueryBuilder builder = new NativeQueryBuilder();
        builder.withQuery(q -> q.match(m -> m.field("displayName").query(keyword)));
        builder.withFilter(q -> q.bool( b -> b.must(m -> m.term(t -> t.field("status").value(SysConstant.DEFAULT_ENABLE)))));
        builder.withPageable(PageRequest.of(page - 1, size));

        // es搜索结果
        SearchHits<UserESIndex> search = elasticsearchTemplate.search(builder.build(), UserESIndex.class);
        // 无命中的数据
        if (!search.hasSearchHits()) {
            return Result.success(new Page<>(page, size, 0));
        }

        Page<UserDetailsVo> voPage = new Page<>(page, size, search.getTotalHits());

        // 设置结果
        List<UserDetailsVo> collect = search.getSearchHits().stream().map(x -> {
            UserDetailsVo vo = new UserDetailsVo();
            vo.setDisplayName(x.getContent().getDisplayName());
            vo.setUsername(x.getContent().getUsername());
            vo.setAvatar(x.getContent().getAvatar());
            vo.setSex(x.getContent().getSex());
            return vo;
        }).toList();
        avatarUtilz.setAvatarUrls(collect);
        voPage.setRecords(collect);

        return Result.success(voPage);
    }




}
